package com.shihan.rabbitmq.demo.listener;

import com.rabbitmq.client.Channel;
import com.shihan.rabbitmq.demo.config.RabbitMQConfig;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Description Spring Boot 方式的消息异步监听回调的方法
 * @Author shihan
 * @Date 2021/1/9 22:54
 * @Version 1.0
 */
@Component
public class MyMessageListener {

    /**
     * 注解指明 监听的队列 & 消息确认的方式为手动确认
     * @param channel
     * @param message
     * @param msgStr
     * @param deliveryTag
     */
    @RabbitListener(queues = {RabbitMQConfig.QUEUE_NAME_DELAYED}, ackMode = "MANUAL")
    public void delayedMessageListener(Channel channel,
                                       Message message,
                                       @Payload String msgStr,
                                       @Header(AmqpHeaders.DELIVERY_TAG) Integer deliveryTag) {
        System.out.println("【延迟消息--接收到的消息为：】" + msgStr);
        try {
            channel.basicAck(deliveryTag,false);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("【消息确认出现异常！】");
        }
    }

    /**
     * 注解指明 监听的队列 & 消息确认的方式为手动确认
     * @param channel
     * @param message
     * @param msgStr
     * @param deliveryTag
     */
    @RabbitListener(queues = {RabbitMQConfig.QUEUE_NAME_COMM}, ackMode = "MANUAL")
    public void commMessageListener(Channel channel,
                                       Message message,
                                       @Payload String msgStr,
                                       @Header(AmqpHeaders.DELIVERY_TAG) Integer deliveryTag) {
        System.out.println("【普通消息--接收到的消息为：】" + msgStr);
        try {
            channel.basicAck(deliveryTag,false);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("【消息确认出现异常！】");
        }
    }

}
